package com.li.taskcenter.quartz.config;

import com.li.taskcenter.quartz.QuartzDemo;
import com.li.taskcenter.quartz.QuartzToSpringIoc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * @description: Quartz配置类
 * @author: Lidong
 * @time: 2020/6/20 15:47
 **/
@Configuration
public class QuartzConfig {

    /**
     * 1.创建Job对象
     */
    @Bean
    public JobDetailFactoryBean jobDetailFactoryBean() {
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        //关联自己的Job类
        jobDetailFactoryBean.setJobClass(QuartzDemo.class);
        return jobDetailFactoryBean;
    }

    /**
     * 2.创建Tigger对象：简单的Trigger
     */
//    @Bean
//    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean) {
//        SimpleTriggerFactoryBean simpleTriggerFactoryBean = new SimpleTriggerFactoryBean();
//        //关联JobDetail对象
//        simpleTriggerFactoryBean.setJobDetail(jobDetailFactoryBean.getObject());
//        //设置方法触发时间
//        simpleTriggerFactoryBean.setRepeatInterval(2000);
//        //设置重复次数
//        simpleTriggerFactoryBean.setRepeatCount(3);
//        return simpleTriggerFactoryBean;
//    }

    /**
     * Cron Trigger
     */
    @Bean
    public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean) {
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        //关联JobDetail对象
        cronTriggerFactoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        //设置触发时间
        cronTriggerFactoryBean.setCronExpression("0/2 * * * * ?");

        return cronTriggerFactoryBean;
    }

    /**
     * 3.创建Scheduler对象
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean simpleTriggerFactoryBean, QuartzToSpringIoc quartzToSpringIoc) {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        //关联Trigger
        schedulerFactoryBean.setTriggers(simpleTriggerFactoryBean.getObject());
        //将我们的配置类
        schedulerFactoryBean.setJobFactory(quartzToSpringIoc);
        return schedulerFactoryBean;
    }
}
